package edu.zzuli.common.security;

import java.util.Iterator;

import org.acegisecurity.Authentication;
import org.acegisecurity.ConfigAttributeDefinition;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.intercept.web.AbstractFilterInvocationDefinitionSource;

public class DBFilterInvocationDefinitionSource extends AbstractFilterInvocationDefinitionSource {

	@SuppressWarnings("unused")
	private boolean CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON;

	private DBUrlSourceManager dbUrlSourceManager;

	private boolean showRequestUrl;
	
	private boolean showProtectedResource;

	public void setCONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON(boolean CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON) {
		this.CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON = CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON;
	}

	public void setDbUrlSourceManager(DBUrlSourceManager dbUrlSourceManager) {
		this.dbUrlSourceManager = dbUrlSourceManager;
	}

	public void setShowRequestUrl(boolean showRequestUrl) {
		this.showRequestUrl = showRequestUrl;
	}
	public void setShowProtectedResource(boolean showProtectedResource) {
		this.showProtectedResource = showProtectedResource;
	}

	public ConfigAttributeDefinition lookupAttributes(String url) {
		if (showProtectedResource)
			System.out.println("[DBFilterInvocationDefinitionSource]Protected Resource-->"+this.dbUrlSourceManager.getUrlMap());
		if (showRequestUrl) 
			System.out.println("[DBFilterInvocationDefinitionSource]Request URL-->" + url);
		String url_C = url;
		if (url.indexOf("/") == 0) {	// 数据库中的功能地址不能以“/”开头
			url_C = url_C.substring(1);
		}
		url_C = this.dbUrlSourceManager.convertUrl(url_C);
		if (showProtectedResource) {
			Authentication au = SecurityContextHolder.getContext().getAuthentication();
			if (au != null) {
				System.out.println("acegi_au:au.getName()=" + au.getName());
				System.out.println("acegi_au:au.getAuthorities().length=" + au.getAuthorities().length);
				for (int i = 0; i < au.getAuthorities().length; i++) {
					System.out.println("acegi_au:au.getAuthorities()[" + i + "].getAuthority()=" + au.getAuthorities()[i].getAuthority());
				}
				System.out.println("acegi_au:(String)au.getCredentials()=" + (String) au.getCredentials());
				System.out.println("acegi_au:au.getDetails()[org.acegisecurity.ui.WebAuthenticationDetails]=" + au.getDetails().toString());
				System.out.println("acegi_au:au.getPrincipal()[org.acegisecurity.userdetails.User]=" + au.getPrincipal());
			}
		}
		return (ConfigAttributeDefinition) this.dbUrlSourceManager.getUrlMap().get(url_C);
	}

	public Iterator getConfigAttributeDefinitions() {
		return this.dbUrlSourceManager.getUrlMap().values().iterator();
	}

}
